import sys
import threading
import queue
import time
import numpy as np
import cv2 as cv
import numpy
from WiFi.protocol import createPacks

#============================#
#   发送数据
#============================#
class Transmitter():

    #----------------------#
    #   初始化发送器
    #----------------------#
    def __init__(self, sock, recver_ip = '127.0.0.1', port = 5600, sys_id = 0 , chunk_size = 1024):
        self.run = False
        self.sock = sock
        self.recver_ip = recver_ip
        self.port = port
        self.sys_id = sys_id
        if( chunk_size <= 1024 and chunk_size > 0 ):
            self.chunk_size = chunk_size
        else:
            self.chunk_size = 1024
        self.send_buffer = queue.Queue(10)
        self.img_buffer = queue.Queue(2)
        self.txStart()

    #----------------------#
    #   开始发送
    #----------------------#
    def txStart(self):
        if self.run == True:
            return
        self.imgEncodeThread = threading.Thread(target=self.imgEncodeLoop)
        self.sendThread = threading.Thread(target=self.sendLoop)
        self.run = True
        self.imgEncodeThread.start()
        self.sendThread.start()

    #----------------------#
    #   手动停止发送
    #----------------------#
    def txStop(self):
        self.run = False
        time.sleep(1)

    #----------------------#
    #   把数据放到发送队列里
    #----------------------#
    def sendMessage(self,msg_id,data):
        if( self.send_buffer.full() ):
            try:    self.send_buffer.get(timeout=0.005)
            except: pass
        self.send_buffer.put((msg_id,data),False)

    #----------------------#
    #   把图像放到待处理队列里
    #----------------------#
    def sendimg(self,img):
        if( self.img_buffer.full() ):
            try:    self.img_buffer.get(timeout=0.005)
            except: pass
        self.img_buffer.put(img,False)

    #----------------------#
    #   图像处理线程
    #----------------------#
    def imgEncodeLoop(self):
        while self.run:
            try:
                img = self.img_buffer.get()
                #cv.imshow('encode',img)
                #cv.waitKey(1)
                img_encode = cv.imencode('.jpg',img)[1]
                data = numpy.array(img_encode)
                data = data.tostring()
                #print(len(data))
                self.sendMessage(0,data)
                #print('encode ok')
            except:
                print('图像编码失败')
    #----------------------#
    #   数据发送线程
    #----------------------#    
    def sendLoop(self):
        tim = 0
        while self.run:
            try:
                if tim == 0xffffffff:
                    tim = 0
                else:
                    tim += 1
                msg_id,data = self.send_buffer.get()
                packs,fec_packs = createPacks(tim,self.chunk_size,self.sys_id,msg_id,data)
                for i in range(len(packs)):
                    pack = packs[i]
                    self.sock.sendto(pack,(self.recver_ip,self.port))

                for i in range(len(fec_packs)):
                    pack = fec_packs[i]
                    self.sock.sendto(pack,(self.recver_ip,self.port))
            except:
                print('发送失败')
                self.txStop()
                
